// web/src/actions/learn/get-progress.ts
import {db} from '@/lib/db'

export const getProgress = async (
    userId: string,
    courseId: string
): Promise<number> => {
    try {
        const publishedChapters = await db.chapter.findMany({
            where: {
                courseId: courseId,
                isPublished: true
            },
            select: {
                id: true
            }
        })

        // chapter[] 转为 string(id)[]
        const publishedChapterIds = publishedChapters.map((c) => c.id)

        // 当前已经完成的进度
        const validCompletedChapters = await db.userProgress.count({
            where: {
                userId: userId,
                chapterId: {
                    in: publishedChapterIds
                },
                isCompleted: true
            }
        })

        const progressPercentage = (validCompletedChapters / publishedChapterIds.length) * 100

        return progressPercentage
    } catch (err) {
        console.error('[GET_PROGRESS]', err)
        return 0
    }
}